package cn.iocoder.yudao.module.system.controller.admin.user;

import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserAssetsPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserAssetsRespVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserAssetsSaveReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserAssetsGrantVipReqVO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserAssetsClaimVipRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.UserAssetsDO;
import cn.iocoder.yudao.module.system.service.user.UserAssetsService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import java.util.*;
import java.io.IOException;
import java.time.LocalDateTime;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;


@Tag(name = "管理后台 - 用户资源")
@RestController
@RequestMapping("/system/ai/user-assets")
@Validated
public class UserAssetsController {

    @Resource
    private UserAssetsService userAssetsService;

    @PostMapping("/create")
    @Operation(summary = "创建用户资源")
    @PreAuthorize("@ss.hasPermission('ai:user-assets:create')")
    public CommonResult<Integer> createUserAssets(@Valid @RequestBody UserAssetsSaveReqVO createReqVO) {
        return success(userAssetsService.createUserAssets(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新用户资源")
    @PreAuthorize("@ss.hasPermission('ai:user-assets:update')")
    public CommonResult<Boolean> updateUserAssets(@Valid @RequestBody UserAssetsSaveReqVO updateReqVO) {
        userAssetsService.updateUserAssets(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除用户资源")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('ai:user-assets:delete')")
    public CommonResult<Boolean> deleteUserAssets(@RequestParam("id") Integer id) {
        userAssetsService.deleteUserAssets(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得用户资源")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('ai:user-assets:query')")
    public CommonResult<UserAssetsRespVO> getUserAssets(@RequestParam("id") Integer id) {
        UserAssetsDO userAssets = userAssetsService.getUserAssets(id);
        return success(BeanUtils.toBean(userAssets, UserAssetsRespVO.class));
    }

    @GetMapping("/getByUserId")
    @Operation(summary = "获得用户资源")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PermitAll
    public CommonResult<UserAssetsRespVO> getUserAssets(@RequestParam("userId") Long userId) {
        UserAssetsDO userAssets = userAssetsService.getUserAssetsByUserId(userId);
        return success(BeanUtils.toBean(userAssets, UserAssetsRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得用户资源分页")
    @PreAuthorize("@ss.hasPermission('ai:user-assets:query')")
    public CommonResult<PageResult<UserAssetsRespVO>> getUserAssetsPage(@Valid UserAssetsPageReqVO pageReqVO) {
        PageResult<UserAssetsDO> pageResult = userAssetsService.getUserAssetsPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, UserAssetsRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出用户资源 Excel")
    @PreAuthorize("@ss.hasPermission('ai:user-assets:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportUserAssetsExcel(@Valid UserAssetsPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<UserAssetsDO> list = userAssetsService.getUserAssetsPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "用户资源.xls", "数据", UserAssetsRespVO.class,
                        BeanUtils.toBean(list, UserAssetsRespVO.class));
    }

    @PostMapping("/grant-simulation-vip")
    @Operation(summary = "为用户授予模拟志愿VIP")
    @PreAuthorize("@ss.hasPermission('ai:user-assets:update')")
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> grantSimulationVip(@Valid @RequestBody UserAssetsGrantVipReqVO reqVO) {
        boolean result = userAssetsService.grantSimulationVip(reqVO.getUserId(), reqVO.getDays());
        return success(result);
    }

    @PostMapping("/grant-simulation-vip-7days")
    @Operation(summary = "为用户自动授予7天模拟志愿VIP")
    @PermitAll
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> grantSimulationVip7Days(@RequestParam("userId") Long userId) {
        boolean result = userAssetsService.grantSimulationVip(userId, 7);
        return success(result);
    }

    @GetMapping("/can-claim-simulation-vip")
    @Operation(summary = "判断用户是否可以领取模拟志愿VIP")
    @PermitAll
    public CommonResult<UserAssetsClaimVipRespVO> canClaimSimulationVip(@RequestParam("userId") Long userId) {
        UserAssetsClaimVipRespVO respVO = new UserAssetsClaimVipRespVO();
        respVO.setUserId(userId);

        // 判断是否可以领取
        boolean canClaim = userAssetsService.canClaimSimulationVip(userId);
        respVO.setCanClaim(canClaim);

        // 获取用户资产信息以提供更详细的状态
        UserAssetsDO userAssets = userAssetsService.getUserAssetsByUserId(userId);

        if (userAssets == null) {
            respVO.setHasVipRecord(false);
            respVO.setStatusMessage("用户无VIP记录，可以领取");
            respVO.setVipValid(false);
        } else {
            respVO.setHasVipRecord(true);
            respVO.setVipStartTime(userAssets.getSimulationStartTime());
            respVO.setVipEndTime(userAssets.getSimulationEndTime());

            if (userAssets.getSimulationStartTime() == null && userAssets.getSimulationEndTime() == null) {
                respVO.setStatusMessage("用户无VIP记录，可以领取");
                respVO.setVipValid(false);
            } else {
                // 检查VIP是否有效
                boolean vipValid = userAssets.getSimulationEndTime() != null &&
                                  userAssets.getSimulationEndTime().isAfter(LocalDateTime.now());
                respVO.setVipValid(vipValid);

                if (vipValid) {
                    respVO.setStatusMessage("用户VIP有效，不能重复领取");
                } else {
                    respVO.setStatusMessage("用户VIP已过期，不能重复领取");
                }
            }
        }

        return success(respVO);
    }

}